import { Subject } from "rxjs";
import { finalize } from "rxjs/operators";
import { getLogger } from "../utils";

const log = getLogger("Purpose");
log("Ajax without caching")

const btn = document.createElement("button");
btn.innerText = "Click me";
document.body.appendChild(btn);

function myFromEvent(el: HTMLElement, eventName: string) {
    const sub = new Subject<Event>();
    const cb = sub.next.bind(sub);
    console.log("added event listener");
    el.addEventListener(eventName, cb);
    return sub.asObservable().pipe(finalize(() => {
        el.removeEventListener(eventName, cb);
        console.log("removed event listener");
    }));
}

let count = 5;

const sub = myFromEvent(btn, "click").subscribe(e => {
    count--;
    console.log("Clicked", e);
    if (count === 0) {
        sub.unsubscribe();
    }
});
